package edu.tapestry.iddb.client.pages;

import iddb.ConnectResults;
import iddb.ConnectionFailed;
import iddb.ConnectionResultPOJO;
import iddb.ConnectionSuccessed;

import java.util.ArrayList;
import java.util.List;

import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.ApplicationState;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.beaneditor.BeanModel;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.BeanModelSource;

import edu.tapestry.iddb.client.helpers.DataStorage;
import edu.tapestry.iddb.client.helpers.PI;
import edu.tapestry.iddb.client.pages.groupIM.ListGroupIM;

public class ConnectResultsPage {

	@ApplicationState
	private DataStorage storage;

	@Persist
	@Property
	private ConnectResults connectResult;
	
	@Property
	private ConnectionResultPOJO result;
	
	@Property
	private ConnectionSuccessed resultSuccessed;
	
	@Property
	private ConnectionFailed resultFailed;
	
	@InjectPage
	private ListGroupIM listGroupsPage;

	
	
	@Inject
	private BeanModelSource beanModelSource;

	@Inject
	private ComponentResources resources;

	private BeanModel<ConnectionSuccessed> model;
	
	
	void pageLoaded() {
		this.model = beanModelSource.create(ConnectionSuccessed.class, true, resources
				.getMessages());
		this.model.add("details", null);
		this.model.add("details2", null);
	}
	
	public Object initialize(ConnectResults resp) {
		this.connectResult = resp;
		
		for(ConnectionSuccessed sc : this.getSuccessfull()){
			storage.addPluginIdent(new PI(sc.getIdent()));
		}
		
		return this;
	}
	
	public Object onActionFromGroupsLink(PI ident) {
		return listGroupsPage.initialize(ident.getIdent());
	}
	
	
	public List<ConnectionResultPOJO> getResults(){
		return connectResult.getResults();
	}
	
	public List<ConnectionSuccessed> getSuccessfull(){
		List<ConnectionSuccessed> res = new ArrayList<ConnectionSuccessed>();
		
		for (ConnectionResultPOJO cr : this.connectResult.getResults()){
			if (cr instanceof ConnectionSuccessed){
				res.add((ConnectionSuccessed)cr);
			}
		}
		
		return res;
	}
	
	public List<ConnectionFailed> getFailed(){
		List<ConnectionFailed> res = new ArrayList<ConnectionFailed>();
		
		for (ConnectionResultPOJO cr : this.connectResult.getResults()){
			if (cr instanceof ConnectionFailed){
				res.add((ConnectionFailed)cr);
			}
		}
		
		return res;
	}
	
	public PI getPluginIdentificator(){
		
		return new PI(resultSuccessed.getIdent());
		
	}
}
